//
//  ClassifyViewController.swift
//  clreader
//
//  Created by colin on 2019/3/8.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

class ClassifyViewController: CLBaseViewController {

    private lazy var menuTableView = UITableView(frame: CGRect.zero, style: .plain)
    private var menuData = [JSONObject]()
    private var selectedIndex = -1
    
    private var containers = [Int:UIViewController]()
    
    private lazy var contenetContainer = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        //topBar
        let topBar = CLNavigationBar().then {
            $0.title = "分类"
            $0.backHandle = { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            }
        }
        topBar.show(inView: self.view)
        
        self.view.addSubview(self.menuTableView)
        self.menuTableView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalTo(topBar.snp.bottom)
            make.width.equalTo(95.0)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        self.menuTableView.do {
            $0.backgroundColor = UIColor(hex: "F8F8F8")
            $0.separatorStyle = .none
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.estimatedRowHeight = 0
            $0.register(MenuCell.self, forCellReuseIdentifier: MenuCell.reuseId)
            $0.dataSource = self
            $0.delegate = self
        }
        
        self.view.addSubview(self.contenetContainer)
        self.contenetContainer.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.left.equalTo(self.menuTableView.snp.right)
            make.top.equalTo(topBar.snp.bottom)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        self.refresh()
    }

}

extension ClassifyViewController {
    
    private func selectCat(index:Int) {
        if index != self.selectedIndex {
            
            // 移除旧的
            if let con = self.containers[self.selectedIndex] {
                con.removeFromParent()
                con.view.removeFromSuperview()
            }
        
            // 添加新的
            var controller:UIViewController
            if let con = self.containers[index] {
                controller = con
            } else {
                controller = ClassifyContentViewController(cat_id: self.menuData[index]["cat_id"] as? Int)
                //self.containers[index] = controller
            }
            
            self.contenetContainer.addSubview(controller.view)
            controller.view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            self.addChild(controller)
            controller.didMove(toParent: self)
            
            self.selectedIndex = index
            self.menuTableView.reloadData()
        }
        
    }
    
    private func refresh() {
        
        self.hud.showProgress()
        _ = Router.goods_catlist.request { [weak self] (response:RequestResponse<[JSONObject]>) in
            self?.hud.hide()
            if case .success(let successData,_) = response {
                if let cats = successData {
                    self?.menuData = cats
                } else {
                    self?.menuData = []
                }
                self?.menuTableView.reloadData()
                // 默认选中第一个
                self?.selectCat(index: 0)
            }
            
            if case .failure(_,let message) = response {
                self?.hud.showText(message)
            }
        }
        
    }
    
}

extension ClassifyViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.menuData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MenuCell.reuseId) as! MenuCell
        cell.refresh(data: self.menuData[indexPath.row], selected: self.selectedIndex == indexPath.row)
        return cell
    }
}

extension ClassifyViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return MenuCell.height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectCat(index: indexPath.row)
    }
}

extension ClassifyViewController {
    class MenuCell: UITableViewCell {
        
        static let height:CGFloat = 45.0
        static let reuseId = "MenuCell"
        
        private lazy var labelTitle = UILabel()
        private lazy var viewTag = UIView()
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.selectionStyle = .none
            self.backgroundColor = UIColor.clear
            
            self.labelTitle.do {
                $0.textColor = UIColor(hex: "343434")
                $0.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
            }
            self.contentView.addSubview(self.labelTitle)
            self.labelTitle.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15.0)
                make.centerY.equalToSuperview()
            }
            
            self.viewTag.backgroundColor = UIColor(hex: "B93624")
            self.contentView.addSubview(self.viewTag)
            self.viewTag.snp.makeConstraints { (make) in
                make.left.equalToSuperview()
                make.size.equalTo(CGSize(width: 3.0, height: 15.0))
                make.centerY.equalToSuperview()
            }
        }
        
        func refresh(data:JSONObject?,selected:Bool) {
            self.labelTitle.text = data?["cat_name"] as? String
            
            if selected {
                self.labelTitle.textColor = UIColor(hex: "B93624")
                self.viewTag.isHidden = false
                self.contentView.backgroundColor = UIColor.white
            } else {
                self.labelTitle.textColor = UIColor(hex: "343434")
                self.viewTag.isHidden = true
                self.contentView.backgroundColor = UIColor.clear
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}
